//
//  HMRefreshControl.swift
//  01-自定义下拉刷新控件
//
//  Created by 赵少朋赵少朋 on 2017/2/9.
//  Copyright © 2017年 ITheima. All rights reserved.
//

import UIKit

//高度
private let refreshHeight:CGFloat = 50

//枚举
enum HMRefreshControlType: String {

    case normal = "正常中"
    case pulling = "下拉中"
    case refreshing = "刷新中"
}

class HMRefreshControl: UIControl {

    ///全局变量 保存要添加到的父视图
    var scrollView:UIScrollView?
    
    // 实时记录刷新控件的状态
    var refreshType:HMRefreshControlType = .normal {
        
        
        didSet {
            
            messageLabel.text = refreshType.rawValue
            switch refreshType {
            case .normal:
                
                //设置箭头动画
                UIView.animate(withDuration: 0.25, animations: { 
                    
                    self.arrowheadView.transform = CGAffineTransform.identity
                })
                
                // 判断上一个状态是否在刷新中
                if oldValue == .refreshing {
                    
                    UIView.animate(withDuration: 0.25, animations: { 
                        
                        self.scrollView?.contentInset.top = self.scrollView!.contentInset.top - refreshHeight
                    }, completion: { (_) in
                        // 显示箭头 和 风火轮停止动画
                        self.rotateView.stopAnimating()
                        self.arrowheadView.isHidden = false
                    })
                    
                }
                
            case .pulling:
                //设置箭头动画
                self.arrowheadView.transform = CGAffineTransform(rotationAngle: CGFloat(-3 * M_PI))
            case .refreshing:
                
                //刷新中
                UIView.animate(withDuration: 0.25, animations: { 
                    
                    //隐藏箭头和显示风火轮
                    self.rotateView.startAnimating()
                    self.arrowheadView.isHidden = true
                    self.scrollView?.contentInset.top = self.scrollView!.contentInset.top + refreshHeight
                }, completion: { (_) in
                    
                    self.sendActions(for: UIControlEvents.valueChanged)
                })
            }
            
        }
    }
    
    //停止刷新
    func endRefreshing() -> Void {
        refreshType = .normal
    }
    
    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: -refreshHeight, width: UIScreen.main.bounds.width, height: refreshHeight))
        
        backgroundColor = UIColor.orange
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 监听控件要加载到谁身上
    override func willMove(toSuperview newSuperview: UIView?) {
        
        //判断是否是为空 且是可以滚动
        guard let scrollView = newSuperview as? UIScrollView else {
            return
        }
        
        self.scrollView = scrollView
        // 要监听tableView滚动的contentOffset
        ///  使用KVO观察者模式
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.new, context: nil)
        
    }
    /// 监听到属性的改变
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        

        let offsetY = self.scrollView!.contentOffset.y
        /// 临界值 114
        let maxY:CGFloat = self.scrollView!.contentInset.top + refreshHeight
        
        /// 判断是否在拖动
        if self.scrollView!.isDragging {
            
            /// 判断是否为正常
            if offsetY >= -maxY && refreshType == .pulling {
                
                
                refreshType = .normal
            
                
            } else if offsetY < -maxY && refreshType == .normal {
                //下拉中
                refreshType = .pulling
            }
        } else {
            
            if refreshType == .pulling {
                //刷新中
                refreshType = .refreshing
                
            }
            
        }
        
    }

    
    /// MARK: 设置视图
    func setupUI() -> Void {
        
        addSubview(arrowheadView)
        addSubview(messageLabel)
        addSubview(rotateView)
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0))
        
        arrowheadView.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: arrowheadView, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: messageLabel, attribute: NSLayoutAttribute.left, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: arrowheadView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: messageLabel, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0))
        
        rotateView.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: rotateView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: arrowheadView, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: rotateView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: messageLabel, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0))
        
    }
    
    // MARK: 懒加载控件
    fileprivate lazy var arrowheadView:UIImageView = {
    
        let imgView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
        
        return imgView
    }()
    
    // 风火轮
    fileprivate lazy var rotateView:UIActivityIndicatorView = {
    
        let actView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
        actView.isHidden = true
        
        return actView
    }()
    
    fileprivate lazy var messageLabel:UILabel = {
    
        let lab = UILabel()
        lab.textColor = UIColor.white
        lab.text = "正常中"
        lab.font = UIFont.systemFont(ofSize: 12)
        return lab
    }()
    //移除观察者
    deinit {
        self.scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
}
